package cn.stylefeng.guns.modular.system.controller;

import cn.hutool.core.date.DateTime;
import cn.stylefeng.guns.core.common.annotion.Permission;
import cn.stylefeng.guns.core.common.cons.GeneralTypeEnum;
import cn.stylefeng.guns.core.common.constant.Const;
import cn.stylefeng.guns.core.common.exception.BizExceptionEnum;
import cn.stylefeng.guns.core.common.util.DateUtil;
import cn.stylefeng.guns.core.log.LogObjectHolder;
import cn.stylefeng.guns.core.shiro.ShiroKit;
import cn.stylefeng.guns.modular.system.entity.Activity;
import cn.stylefeng.guns.modular.system.model.ActivityDto;
import cn.stylefeng.guns.modular.system.service.ActivityService;
import cn.stylefeng.guns.modular.system.warpper.ActivityWarpper;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.RequestEmptyException;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.time.DateUtils;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 活动功能
 */
@Controller
@RequestMapping("/activity")
public class ActivityController extends BaseController {

    private static String PREFIX = "/system/activity/";

    @Autowired
    private ActivityService activityService;


    /**
     * 跳转到活动详情页面
     */
    @RequestMapping("")
    public String activity(){
        return PREFIX + "activity.html";
    }

    /**
     * 跳转到增加活动页面
     */
    @Permission
    @RequestMapping("/activity_add")
    public String activityAdd(){
        return PREFIX + "activity_add.html";
    }

    /**
     * 跳转到修改活动详情页面
     */
    @Permission
    @RequestMapping("/activity_edit")
    public String activityEdit(@RequestParam Long activityId) {
        if (ToolUtil.isEmpty(activityId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        Activity activity = this.activityService.getById(activityId);
        LogObjectHolder.me().set(activity);
        return PREFIX + "activity_edit.html";
    }


    /**
     * 添加活动
     *
     * @author fengshuonan
     */
    @RequestMapping("/add")
    @Permission
    @ResponseBody
    public ResponseData add(@Valid ActivityDto activity, BindingResult result) {
        if (result.hasErrors()) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        if (DateUtil.getDifference(activity.getEndTime(), activity.getStartTime()) < 0){
            throw new ServiceException(BizExceptionEnum.DATE_DIFFERENCE);
        }
        Activity copy = new Activity();
        BeanUtils.copyProperties(activity,copy);
        copy.setIsTimeout(GeneralTypeEnum.DEFAULT_TIMEOUT.getCode());
        this.activityService.save(copy);
        return SUCCESS_TIP;
    }

    /**
     * 更新活动信息
     */
    @RequestMapping("/edit")
    @ResponseBody
    public ResponseData edit(@Valid ActivityDto activity, BindingResult result) {
        if (result.hasErrors()) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        if (DateUtil.getDifference(activity.getEndTime(), activity.getStartTime()) < 0){
            throw new ServiceException(BizExceptionEnum.DATE_DIFFERENCE);
        }
        Activity copy = new Activity();
        BeanUtils.copyProperties(activity,copy);
        this.activityService.updateById(copy);
        return SUCCESS_TIP;
    }


    /**
     * 删除活动
     */
    @RequestMapping("/delete")
    @Permission
    @ResponseBody
    public ResponseData delete(@RequestParam Long activityId) {
        if (ToolUtil.isEmpty(activityId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        this.activityService.removeById(activityId);
        return SUCCESS_TIP;
    }

    /**
     * 获取活动详情
     */
    @RequestMapping("/getActivityInfo")
    @ResponseBody
    public Object getActivityInfo(@RequestParam Long activityId) {
        if (ToolUtil.isEmpty(activityId)) {
            throw new RequestEmptyException();
        }
        Activity activity = activityService.getById(activityId);
        return ResponseData.success(activity);
    }

    /**
     * 查询活动信息
     *
     * @author fengshuonan
     */
    @RequestMapping("/list")
    @Permission
    @ResponseBody
    public Object list(@RequestParam(required = false) String startTime,
                       @RequestParam(required = false) String endTime) {
        List<Map<String, Object>> activitys = null;
        activitys = activityService.selectActivitys(startTime, endTime);
        //检测时间 如果过期就修改为已经过期
        Date now = new Date();
        if (activitys.size() > 0){
            for (Map<String, Object> activity : activitys) {
                Date old = (Date)activity.get("endTime");
                if (DateUtil.getDifference(old, now) < 0){
                    Activity thisClass = JSONObject.parseObject(JSONObject.toJSONString(activity), Activity.class);
                    thisClass.setIsTimeout(GeneralTypeEnum.IS_TIMEOUT.getCode());
                    activityService.updateById(thisClass);
                }
            }
            activitys = activityService.selectActivitys(startTime, endTime);
        }
        return new ActivityWarpper(activitys).wrap();
    }

    /**
     * 领取活动
     */
    @RequestMapping("/toGetById")
    @ResponseBody
    public ResponseData toGetById(@RequestParam Long activityId) {
        Long userId = ShiroKit.getUserNotNull().getId();
        if (ToolUtil.isEmpty(userId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        if (ToolUtil.isEmpty(activityId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        this.activityService.insertThisActivity(userId, activityId);
        return SUCCESS_TIP;
    }
//--------------------------------------------------------------------------
    /**
     * 跳转到我领取的活动
     */
    @RequestMapping("/myActivity")
    public String myActivity(){
        return PREFIX + "myActivity.html";
    }


    /**
     * 查看我领取的活动
     */
    /**
     * 查询车辆列表
     *
     * @author fengshuonan
     */
    @RequestMapping("/activityList")
    @ResponseBody
    public Object activityList() {
        Long userId = ShiroKit.getUserNotNull().getId();
        if (ToolUtil.isEmpty(userId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        List<Long> activityIds = activityService.selectActivityId(userId);
        List<Map<String, Object>> activitys = activityService.selectMyActivitys(activityIds);
        return new ActivityWarpper(activitys).wrap();
    }

    /**
     * 活动表导出
     */
    @RequestMapping("/getMyActivityEls")
    public void getMyRentEls(HttpServletResponse response) throws IOException {
        Long userId = ShiroKit.getUserNotNull().getId();
        if (ToolUtil.isEmpty(userId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        List<Long> activityIds = activityService.selectActivityId(userId);
        List<Map<String, Object>> activitys = activityService.selectMyActivitys(activityIds);
        String fileName = "我的活动信息";
        response.setContentType("application/excel"); //响应类型
        response.setHeader("Content-disposition",
                "attachment;filename=" +
                        fileName +";filename*=utf-8''"+
                        URLEncoder.encode(fileName,"UTF-8")); //响应样式 ，URLEncoder防止中文乱码
        HSSFWorkbook workbook=new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("活动信息表"); //创建sheet并且给定表名
        int rowNum=0;
        String[] headers={"活动名称","活动简介","折扣力度","开始时间","结束时间"}; //第一列中文
        HSSFRow row=sheet.createRow(rowNum); //创建行
        for (int i =0; i <headers.length;i++){
            HSSFCell cell=row.createCell(i);  //通过行创建列
            HSSFRichTextString text=new HSSFRichTextString(headers[i]); //对第一行第一列设置文字或字体
            cell.setCellValue(text);  //创建1行5列成功
        }
        //添加数据
        for (Map<String, Object> activity : activitys) {
            rowNum++;
            HSSFRow row1=sheet.createRow(rowNum);  //每次创建一行
            row1.createCell(0).setCellValue(activity.get("activityName").toString());
            row1.createCell(1).setCellValue(activity.get("activityNote").toString());
            row1.createCell(2).setCellValue(activity.get("activityDiscount").toString() + "折");
            row1.createCell(3).setCellValue(activity.get("startTime").toString());
            row1.createCell(4).setCellValue(activity.get("endTime").toString());
        }
        workbook.write(response.getOutputStream());
    }
}
